#include "incs.h"

#include <sstream>

#include "IGameState.h"
#include "MenuState.h"
#include "CameraController.h"
#include "KeysState.h"

void CameraControl::IsFreeCamera( bool b )
{
	mFreeCamera = b;
}

bool CameraControl::IsFreeCamera() const
{
	return mFreeCamera;
}

CameraControl::CameraControl( Ogre::Camera * cam ) : 
	mCamera(cam), mFreeCamera(true), mSpeed(100.0), mRotSpeed(30.0),
	mDbgShowCameraPosition(true)
{

}

void CameraControl::Update( IGameState * gs, float timeSinceLastFrame, KeysState const & ks,
						   OIS::MouseState const & ms, Ogre::SceneManager * mgr )
{
	using namespace Ogre;

	if(mFreeCamera)
	{

		Vector3 mTranslateVector(0, 0, 0);
		Ogre::Radian mRotX(0), mRotY(0);

		float mMoveScale = mSpeed * timeSinceLastFrame;
		Degree mRotScale(mRotSpeed * timeSinceLastFrame);

		// Update through keys
		//if(ks.IsDown(OIS::KC_I) && !ks.IsDown(OIS::KC_RIGHT))
		//	mTranslateVector = Vector3(0, 0, -mSpeed * timeSinceLastFrame);
		//else if(ks.IsDown(OIS::KC_RIGHT) && !ks.IsDown(OIS::KC_I))
		//	mTranslateVector = Vector3(0, 0, +mSpeed * timeSinceLastFrame);
		if(ks.IsDown(OIS::KC_A))
			mTranslateVector.x = -mMoveScale;	// Move camera left

		if(ks.IsDown(OIS::KC_D))
			mTranslateVector.x = mMoveScale;	// Move camera RIGHT

		if(ks.IsDown(OIS::KC_UP) || ks.IsDown(OIS::KC_W) )
			mTranslateVector.z = -mMoveScale;	// Move camera forward

		if(ks.IsDown(OIS::KC_DOWN) || ks.IsDown(OIS::KC_S) )
			mTranslateVector.z = mMoveScale;	// Move camera backward

		if(ks.IsDown(OIS::KC_PGUP))
			mTranslateVector.y = mMoveScale;	// Move camera up

		if(ks.IsDown(OIS::KC_PGDOWN))
			mTranslateVector.y = -mMoveScale;	// Move camera down

		if(ks.IsDown(OIS::KC_RIGHT))
			mCamera->yaw(-mRotScale);

		if(ks.IsDown(OIS::KC_LEFT))
			mCamera->yaw(mRotScale);



		// Update through mouse.
		if( ms.buttonDown( OIS::MB_Right ) )
		{
			mTranslateVector.x += ms.X.rel * 0.13;
			mTranslateVector.y -= ms.Y.rel * 0.13;
		}
		else
		{
			mRotX = Degree(-ms.X.rel * 0.13);
			mRotY = Degree(-ms.Y.rel * 0.13);
		}

		mCamera->yaw(mRotX);
		mCamera->pitch(mRotY);
		mCamera->moveRelative(mTranslateVector);
	}

	
	if(mDbgShowCameraPosition)
	{
		std::stringstream ss;
		Vector3 const & pos = mCamera->getPosition();
		ss << "X: " << pos.x << " ";
		ss << "Y: " << pos.y << " ";
		ss << "Z: " << pos.z;
		//gs->setDebugText(ss.str());
	}
}